import { _decorator, Component, Node, Label } from "cc";
import { getGlobal, MyGlobal } from "../Global";
const { ccclass, property } = _decorator;

@ccclass("JoinRoom")
export class JoinRoom extends Component {
  //   @property(cc.Prefab)
  //   panel: cc.Prefab;
  @property(cc.Integer)
  current = -1;
  @property({
    type: Label,
    displayName: "label数组",
    multiline: true,
  })
  labels: cc.Label[] = [];
  g: MyGlobal;
  //   @property({ type: Node, multiline: true })
  //   nodes: cc.Node[] = [];
  start() {
    const g = getGlobal();
    this.g = g;
  }

  update(deltaTime: number) {}

  onEnable() {
    this.reset();
  }
  stop(){
    
  }
  reset() {
    for (var i = 0; i < this.labels.length; ++i) {
      this.labels[i].string = "";
    }
    this.current = -1;
  }
  close() {
    this.reset();
    this.node.active = false;
    this.g.userMgr.clearEnter();
  }
  join() {
    let roomId = this.labels
      .map((i) => {
        return i.string;
      })
      .join("");
    const g = getGlobal();
    this.g.userMgr.enterRoom(roomId, (res, res2) => {
      if (res.errcode == 0) {
        this.node.active = false;
      } else {
        var content = "房间[" + roomId + "]不存在，请重新输入!";
        if (res.errcode == 4) {
          content = "房间[" + roomId + "]已满!";
        }
        console.log(g, "?g");
        g.alert.show("提示", content);
        this.reset();
      }
    });
  }
  onInput(e, key) {
    console.log(key, "?key");
    switch (key) {
      case "x":
        this.close();
        break;
      case "reset":
        this.reset();
        break;
      case "delete":
        if (this.current > -1) {
          this.labels[this.current].string = "";
          this.current--;
        }
        break;
      default:
        if (this.current < 5) {
          this.labels[this.current + 1].string = key;
          this.current++;
        }
        if (this.current == 5) {
          this.join();
        }
        break;
    }
  }
}
